import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;


public class Encoder {
	
	private HuffmanTree ht = new HuffmanTree();
	
	public void encodeFile(String origFile, String destFile)
	{
		BitSequence bs = encode(origFile);
		while(bs.size()%8 != 0) bs.append(false);
		writeEncodedFile(destFile, bs);
	}
	
	private BitSequence encode(String fileName)
	{
		BitSequence bs = new BitSequence();
		try(FileInputStream fis = new FileInputStream(fileName)) {
			BufferedReader in = new BufferedReader(new InputStreamReader(fis));
			while(in.ready())
			{
				String s = in.readLine() + System.getProperty("line.separator");
				BitSequence bseq = ht.encode(s);
				bs.append( bseq );
			}
			ht.addEndOfCode(bs);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e)	{
			e.printStackTrace();
		}
		return bs;
	}	
	
	public void writeEncodedFile(String fileDest, BitSequence bs)
	{
		try {
			FileOutputStream fot = new FileOutputStream(fileDest);
			while(!bs.isEmpty())
			{
				fot.write((int)bs.pollChar());
			}
			fot.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e)	{
			e.printStackTrace();
		}
	}
}